<?php
class Model_Visit extends Ac_Model
{
    protected static  $_collection = 'visit';

    /**
     *
     * @var array define the requirements for this model
     */
    protected static $_requirements = array(
    );

	protected static $_transcript = array(
    	'_id'	=> '_id',
        'uid'	=> 'uniqid',
        'us'	=> 'user',
        'obj'	=> 'object',
        'ob_t'	=> 'object_type',
        'c_dt'	=> 'created_at',
        'us_ob'	=> 'user_object',
    );
    
	public function __construct($data = array(), $config = array())
	{
        $config['collection'] = 'visit';
        self::ensureIndex(array('obj'));
        self::ensureIndex(array('us'));
        self::ensureIndex(array('uid'));
        parent::__construct($data, $config);
    }
    
 	public function __get($name)
    {
        if ($name == 'object') {
            return Model_Listing::find($this->obj);
        } elseif($name == 'user') {
            return Model_User::find($this->us);
        } else {
            return parent::__get($name);
        }
    }
	
	public static function visit($id)
    {
		if(empty($id)){ 
			return false;
		}	

        $obj = Model_Listing::find($id);
        if (empty($obj)) {
            return false;
        }
		
		if (Zend_Registry::isRegistered('loggedin_user')) {
            $loggedin_user = Zend_Registry::get('loggedin_user')->_id;
            //$h             = self::one(array('obj' => $obj->_id, 'user' => $loggedin_user));
        } else {
            //generate a unique id and put it in a cookie if it doesn 't exists
            if (empty($_COOKIE['ac_bookmark'])) {
                $uniqid = uniqid('', true);
                setcookie('ac_bookmark', $uniqid, time()+86400*365, "/");
                $_COOKIE['ac_bookmark'] = $uniqid;
            } else {
                $uniqid = $_COOKIE['ac_bookmark'];
            }
            //$h = self::one(array('obj' => $obj->_id, 'uid'=> $uniqid));
        }
        //$count = (int)self::getCount($id);
    	
        //if (empty($h)) {
            $h = new self;
            $h->obj          = $obj->_id;
            $h->user_object  = $obj->us;
            if (!empty($loggedin_user)) {
                $h->user   = $loggedin_user;
            } else {
                $h->uniqid = $uniqid;
            } 
            $h->created_at = new MongoDate(time());
            $h->object_type = $obj->ca;
            $h->save();
        //} 
	}
}